package de.klingbeil.hhcalc.ui.application;

import java.util.Arrays;

import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;

import de.klingbeil.hhcalc.backend.domain.HhcalcItem;

public class ItemFormLayout extends Form {

	private static final long serialVersionUID = 1L;
	private GridLayout itemEditorLayout;

	public ItemFormLayout(BeanItem<HhcalcItem> personItem) {
		setCaption("Item details");

		// Create our layout (3x3 GridLayout)
		itemEditorLayout = new GridLayout(3, 3);

		// Use top-left margin and spacing
		itemEditorLayout.setMargin(true, false, false, true);
		itemEditorLayout.setSpacing(true);

		setLayout(itemEditorLayout);

		// Set up buffering
		setWriteThrough(false); // we want explicit 'apply'
		setInvalidCommitted(false); // no invalid values in datamodel

		// FieldFactory for customizing the fields and adding validators
		setFormFieldFactory(new ItemFieldFactory());
		setItemDataSource(personItem); // bind to POJO via BeanItem

		// Determines which properties are shown, and in which order:
		setVisibleItemProperties(Arrays
				.asList(new String[] { "firstName", "lastName", "countryCode",
						"password", "birthdate", "shoesize" }));

	}

	/*
	 * Override to get control over where fields are placed.
	 */
	@Override
	protected void attachField(Object propertyId, Field field) {
		if (propertyId.equals("firstName")) {
			itemEditorLayout.addComponent(field, 0, 0);
		} else if (propertyId.equals("lastName")) {
			itemEditorLayout.addComponent(field, 1, 0, 2, 0);
		} else if (propertyId.equals("password")) {
			itemEditorLayout.addComponent(field, 0, 2);
		} else if (propertyId.equals("countryCode")) {
			itemEditorLayout.addComponent(field, 0, 1, 2, 1);
		} else if (propertyId.equals("shoesize")) {
			itemEditorLayout.addComponent(field, 1, 2);
		} else if (propertyId.equals("birthdate")) {
			itemEditorLayout.addComponent(field, 2, 2);
		}
	}
}
